package com.newcapec.modules.pass.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newcapec.common.exception.RRException;
import com.newcapec.common.qrcode.QRCodeUtil;
import com.newcapec.common.utils.*;
import com.newcapec.modules.health.entity.CustomerEntity;
import com.newcapec.modules.health.entity.StudentEntity;
import com.newcapec.modules.health.service.CustomerService;
import com.newcapec.modules.health.service.StudentService;
import com.newcapec.modules.oss.cloud.OSSFactory;
import com.newcapec.modules.pass.dao.PassInfoDao;
import com.newcapec.modules.pass.entity.PassInfoEntity;
import com.newcapec.modules.pass.service.PassInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("passInfoService")
public class PassInfoServiceImpl extends ServiceImpl<PassInfoDao, PassInfoEntity> implements PassInfoService {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private AifaceApiUtils aifaceApiUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PassInfoEntity> page = this.baseMapper.selectPageVo(
                new Query<PassInfoEntity>().getPage(params, "id", false), params
        );
        String ossDomain = OSSFactory.getOssDomain();
        page.getRecords().stream().forEach(item -> {
            item.setPhoto(ossDomain + item.getPhoto());
            item.setQrCode(ossDomain + item.getQrCode());
        });
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(PassInfoEntity passInfo) {
        //照片上传至人脸平台
        String ossDomain = OSSFactory.getOssDomain();
        StudentEntity student = studentService.getById(passInfo.getStudentId());
        String studentPhotoUrl = ossDomain + passInfo.getPhoto();
        File photo = null;
        try{
            photo = FileUtils.urlToFile(studentPhotoUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("上传人脸云平台失败,请联系管理员", e);
        }
        AifaceResponse aifaceResponse = aifaceApiUtils.addPerson(photo, student.getStuNo(), student.getName(), 0);
        if(aifaceResponse.getCode() == 1){
            //人脸平台照片核验通过，认证通过
            passInfo.setVerified(1);
            passInfo.setFaceCheck(1);
            passInfo.setFaceUpload(1);
            //照片上传成功并且人脸核对通过，生成二维码
            String url = getQrString(student);
            passInfo.setQrCode(url);
        }else{
            //人脸平台照片核验失败，认证拒绝
            passInfo.setVerified(2);
        }
        FileUtils.delteTempFile(photo);
        Date today = new Date();
        passInfo.setEffectiveTime(today);
        passInfo.setExpiryTime(DateUtils.addDateDays(today, 1));
        return this.save(passInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePhoto(PassInfoEntity passInfo) {
        //照片上传至人脸平台
        String ossDomain = OSSFactory.getOssDomain();
        StudentEntity student = studentService.getById(passInfo.getStudentId());
        String studentPhotoUrl = ossDomain + passInfo.getPhoto();
        File photo = null;
        try{
            photo = FileUtils.urlToFile(studentPhotoUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("上传人脸云平台失败,请联系管理员", e);
        }
        AifaceResponse aifaceResponse = aifaceApiUtils.updatePhoto(photo, student.getStuNo(), 0);
        if(aifaceResponse.getCode() == 1){
            //人脸平台照片核验通过，认证通过
            passInfo.setVerified(1);
            passInfo.setFaceCheck(1);
            passInfo.setFaceUpload(1);
            //照片上传成功并且人脸核对通过，生成二维码
            String url = getQrString(student);
            passInfo.setQrCode(url);
        }else{
            //人脸平台照片核验失败，认证拒绝
            passInfo.setVerified(2);
        }
        FileUtils.delteTempFile(photo);
        return this.updateById(passInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(List<Long> ids) {
        List<PassInfoEntity> list = this.listByIds(ids);
        for (PassInfoEntity passInfo : list) {
            StudentEntity student = studentService.getById(passInfo.getStudentId());
            AifaceResponse aifaceResponse = aifaceApiUtils.removePerson(student.getStuNo());
            if(aifaceResponse.getCode() == 1){
                this.removeById(passInfo.getId());
            }else{
                throw new RRException(aifaceResponse.getMsg());
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generateQrcode(List<Long> ids) {
        List<PassInfoEntity> list = this.listByIds(ids);
        for (PassInfoEntity passInfo : list) {
            StudentEntity student = studentService.getById(passInfo.getStudentId());
            //照片上传成功并且人脸核对通过，生成二维码
            String url = getQrString(student);
            passInfo.setQrCode(url);
        }
        return this.updateBatchById(list);
    }

    @Override
    public PassInfoEntity get(Long id) {
        PassInfoEntity passInfo = this.getById(id);
        String ossDomain = OSSFactory.getOssDomain();
        passInfo.setPhoto(ossDomain + passInfo.getPhoto());
        passInfo.setQrCode(ossDomain + passInfo.getQrCode());
        return passInfo;
    }

    @Override
    public PassInfoEntity getByStudentId(Long studentId) {
        QueryWrapper<PassInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        PassInfoEntity passInfo = this.getOne(queryWrapper);
        if(passInfo != null){
            String ossDomain = OSSFactory.getOssDomain();
            passInfo.setPhoto(ossDomain + passInfo.getPhoto());
            passInfo.setQrCode(ossDomain + passInfo.getQrCode());
        }
        return passInfo;
    }

    private String getQrString(StudentEntity student){
        CustomerEntity customer = customerService.get(student.getCustomerId());
        // 嵌入二维码的图片路径
        String logo = customer.getLogo();
        try {
            // 存放在二维码中的内容
            JSONObject data = new JSONObject();
            data.put("stuNo", student.getStuNo());
            data.put("customerId", customer.getId());
            String text = data.toJSONString();
            //生成二维码
            return QRCodeUtil.encodeAndUpload(text, logo, true);
        } catch (Exception e) {
            throw new RRException("生成二维码有误", e);
        }
    }
}